package com.ruoyi.iot.controller;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.iot.domain.CollectPoint;
import com.ruoyi.iot.domain.CollectTask;
import com.ruoyi.iot.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.SecureRandom;
import java.util.*;


@CrossOrigin
@RestController
@RequestMapping(value = "/collection")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;
    @Autowired
    private TokenService tokenService;
    /**
     * 功能描述 多条件查询采集点
     *
     * @param * @param collectPoint
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:14
     */
    @RequestMapping(value = "/getListByCondition", method = RequestMethod.POST)
    public AjaxResult getListByCondition(@RequestBody CollectPoint collectPoint) {
        List<CollectPoint> collectPointList = collectionService.selectCondition(collectPoint);
        return AjaxResult.success(collectPointList);
    }

//    /**
//     * 根据图片导入采集点数据
//     * cwj
//     **/
//    @RequestMapping(value = "/importCollectByImgs", method = RequestMethod.POST)
//    public AjaxResult importCollectByImgs(@RequestBody CollectParamEntity collectParam) {
//        String imgZipUrl = collectParam.getUploadfileurl();
//        if (imgZipUrl.isEmpty()) {
//            AjaxResult.error();
//        }
//        File folder = new File(imgZipUrl);
//        File[] listOfFiles = folder.listFiles();
//        Map<String, CollectPoint> cpMap = new HashMap<>();
//        for (File file : listOfFiles) {
//            if (file.isFile()) {//判断是否为图片文件
//                String[] array = new String[3];
//                Metadata metaData = getPicMetadata(file);
//                metaData.getDirectories().forEach(v ->
//                        v.getTags().forEach(t -> {
//                            switch (t.getTagName()) {
//                                //经度，转WGS84
//                                case "GPS Longitude":
//                                    String lng = t.getDescription();
//                                    double one = Double.parseDouble(lng.split("°")[0].trim());
//                                    double two = Double.parseDouble(lng.split("°")[1].split("'")[0].trim()) / 60;
//                                    double three = Double.parseDouble(lng.split("°")[1].split("'")[1].split("\"")[0].trim()) / 3600;
//                                    array[0] = one + two + three + "";
//                                    break;
//                                //纬度
//                                case "GPS Latitude":
//                                    String lat = t.getDescription();
//                                    double oneLat = Double.parseDouble(lat.split("°")[0].trim());
//                                    double twoLat = Double.parseDouble(lat.split("°")[1].split("'")[0].trim()) / 60;
//                                    double threeLat = Double.parseDouble(lat.split("°")[1].split("'")[1].split("\"")[0].trim()) / 3600;
//                                    array[1] = oneLat + twoLat + threeLat + "";
//                                    break;
//                                //拍摄时间
//                                case "Date/Time Original":
//                                    array[2] = t.getDescription();
//                                default:
//                                    break;
//                            }
//                        }));
//                //文件存到指定路径
//                if (cpMap.containsKey(array[0] + ";" + array[1])) {
//                    CollectPoint cp = cpMap.get(array[0] + ";" + array[1]);
//                    String pointImgUrl = cp.getPointimgurl();
//                    pointImgUrl = pointImgUrl + ';' + file.getName();
//                    cp.setPointimgurl(pointImgUrl);
//                    cpMap.put(array[0] + ";" + array[1], cp);
//                } else {
//                    CollectPoint cp = new CollectPoint();
//                    String geom = "POINT(" + array[0] + " " + array[1] + ")";
//                    County counties = collectionService.dataMatching(geom);
//                    cp.setProvinceCode(counties.getSadcode());
//                    cp.setProvinceName(counties.getProvince());
//                    cp.setCityCode(counties.getCadcode());
//                    cp.setCountyCode(counties.getXadcode());
//                    cp.setCountyName(counties.getCounty());
//                    cp.setLongitude(array[0]);
//                    cp.setLatitude(array[1]);
//                    cp.setPointtype("SP");
//                    cp.setCollectionTime(array[2]);
//                    cp.setPointimgurl(file.getName());
//                    cp.setCreateuserId(collectParam.getUploaduser());
//                    cp.setCreateuserName(collectParam.getUsername());
//                    cp.setOrgId(collectParam.getOrgid());
//                    cp.setGeom(geom);
//                    cpMap.put(array[0] + ";" + array[1], cp);
//                }
//            }
//        }
//        List<CollectPoint> cpoints = new ArrayList<CollectPoint>();
//        for (Map.Entry<String, CollectPoint> entry : cpMap.entrySet()) {
//            cpoints.add(entry.getValue());
//        }
//        ;
//        int insertCount = collectionService.insertCollectPoints(cpoints);
//        returnData.setData(insertCount);
//        return returnData;
//    }

//    /**
//     * 导出采集点（execl +图片文件夹）
//     */
//    /*获取图片数据*/
//    public static Metadata getPicMetadata(File picFile) {
//        Metadata metadata = null;
//        try (InputStream inputStream = new FileInputStream(picFile);
//             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
//            FileType fileType = FileTypeDetector.detectFileType(bufferedInputStream);
//
//            switch (fileType) {
//                case Png:
//                    metadata = PngMetadataReader.readMetadata(picFile);
//                    break;
//                case Jpeg:
//                    metadata = JpegMetadataReader.readMetadata(picFile);
//                    break;
//                default:
//                    return metadata;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return metadata;
//    }

    /**
     * 功能描述 删除采集点
     *
     * @param * @param ID
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:13
     */
    @PostMapping(value = "/deleteCollection")
    public AjaxResult deleteCollection(String ID) {
        int isok = collectionService.deleteCollection(ID);
        return AjaxResult.success(isok);
    }

    /**
     * 功能描述  批量删除采集点
     *
     * @param * @param ids
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:13
     */
//    @RequestMapping(value = "/batchDeleteCollection", method = RequestMethod.POST)
//    public Result batchDeleteCollection(@RequestBody String[] ids) {
//        Result result = new Result();
//        boolean isok = collectionService.batchDeleteCollection(ids);
//        result.setData(isok);
//        return result;
//
//    }

    /**
     * 功能描述 修改采集数据
     *
     * @param * @param collectPoint
     * @return com.agri.collection_server.util.Result<java.lang.Boolean>
     * @author shill
     * @date 2021-02-04 10:13
     */
    @PostMapping(value = "/updateCollection")
    public AjaxResult updateCollection(@RequestBody CollectPoint collectPoint) {
        boolean isok = collectionService.updateCollection(collectPoint);
        return AjaxResult.success(isok);
    }


    /**
     * 功能描述 新增采集数据
     *
     * @param * @param collectPoint
     * @return com.agri.collection_server.util.Result<java.lang.Boolean>
     * @author shill
     * @date 2021-03-15 10:13
     */
//    @RequestMapping(value = "/saveCollection", method = RequestMethod.POST)
//    public Result<Boolean> saveCollection(@RequestBody CollectPoint collectPoint) {
//        Result result = new Result();
//        System.out.println("采集点==" + collectPoint.toString());
//        String geom = "POINT(" + collectPoint.getLongitude();
//        String geom1 = collectPoint.getLatitude() + ")";
//        County counties = collectionService.dataMatching(geom + " " + geom1);
//        collectPoint.setProvinceCode(counties.getSadcode());
//        collectPoint.setProvinceName(counties.getProvince());
//        collectPoint.setCityCode(counties.getCadcode());
//        collectPoint.setCityName(counties.getCity());
//        collectPoint.setCountyCode(counties.getXadcode());
//        collectPoint.setCountyName(counties.getCounty());
//        if (collectPoint.getId() == null || collectPoint.getId().equals("")) {
//            collectPoint.setId(getGUID());
//        }
//        Date day = new Date();
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        collectPoint.setCreateDate(df.format(day));
//        CollectPoint query = collectionService.selectById(collectPoint.getId());
//        boolean isok = false;
//        if (query != null) {
//            isok = collectionService.updateCollection(collectPoint);
//        } else {
//            isok = collectionService.saveCollection(collectPoint);
//        }
//        if (isok && collectPoint.getTaskId() != null && !collectPoint.getTaskId().equals("")) {
//            //修改taskid的状态
//            boolean isupdate = collectionService.updatetaskbyid(collectPoint.getTaskId());
//            System.out.print(isupdate);
//        }
//        mqttGateway.sendToMqtt(collectPoint.tojson(), "Collection/ImportMsg");
//        System.out.println("mqtt==" + collectPoint.tojson());
//        result.setData(isok);
//        return result;
//    }

    /**
     * 功能描述 单删
     *
     * @param * @param collectTask
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:13
     */
    @PostMapping(value = "/deleteTask")
    public AjaxResult deleteTask(@RequestBody CollectTask collectTask) {
        int isok = collectionService.deleteTask(collectTask.getId());
        return AjaxResult.success(isok);
    }

    /**
     * 功能描述 批量删除任务点
     *
     * @param * @param ids
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:12
     */
//    @RequestMapping(value = "/batchDeleteTask", method = RequestMethod.POST)
//    public Result batchDeleteTask(@RequestBody String[] ids) {
//        Result result = new Result();
//        boolean isok = collectionService.batchDeleteTask(ids);
//        String del_ids = "";
//        for (int i = 0; i < ids.length; i++) del_ids += ids[i] + ",";
//        del_ids = del_ids.substring(0, del_ids.length() - 1);
//        mqttGateway.sendToMqtt(del_ids, "Collection/DeleteTasksMsg");
//        result.setData(isok);
//        return result;
//
//    }

    /**
     * 功能描述 修改任务数据
     *
     * @param * @param collectTask
     * @return com.agri.collection_server.util.Result<java.lang.Boolean>
     * @author shill
     * @date 2021-02-04 10:12
     */
    @PostMapping(value = "/updateTask")
    public AjaxResult updateTask(@RequestBody CollectTask collectTask) {
        boolean isok = collectionService.updateTask(collectTask);
        return AjaxResult.success(isok);
    }


    /**
     * 功能描述 保存任务点
     *
     * @param * @param collectTask
     * @return com.agri.collection_server.util.Result<java.lang.Boolean>
     * @author shill
     * @date 2021-02-04 10:12
     */
    @PostMapping(value = "/saveTask")
    public AjaxResult saveTask(@RequestBody CollectTask collectTask) {
//        Result result = new Result();
//        System.out.println("save参数=" + collectTask);
//        String username = (String) httpSession.getAttribute("username");
//        System.out.println("username==" + username);
//        collectTask.setCreatename(username);
//        LoginUser loginUser = tokenService.getLoginUser(request);
//        collectTask.setCreatename(loginUser.getUsername());
        String taskId= IdUtils.simpleUUID();
        collectTask.setId(taskId);
        boolean isok = collectionService.saveTask(collectTask);
//		JSONObject json = JSONObject.fromObject(collectTask);
//        System.out.println(collectTask.tojson());
//        mqttGateway.sendToMqtt(collectTask.tojson(), "Collection/ImportTaskMsg");
//        result.setData(isok);
        return AjaxResult.success(isok);
    }


    /**
     * 功能描述 根据任务id查询采集数据
     *
     * @param * @param collectTask
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:11
     */
    @RequestMapping(value = "/getListByTaskId", method = RequestMethod.POST)
    public AjaxResult getListByTaskId(@RequestBody CollectTask collectTask) {
        List<CollectPoint> collectPointList = collectionService.getListByTaskId(collectTask);
        return AjaxResult.success(collectPointList);
    }

    /**
     * 功能描述 解除任务数据关联
     *
     * @param * @param collectPoint
     * @return com.agri.collection_server.util.Result<java.lang.Boolean>
     * @author shill
     * @date 2021-02-04 10:11
     */
//    @RequestMapping(value = "/disassociateData", method = RequestMethod.POST)
//    public Result<Boolean> disassociateData(@RequestBody CollectPoint collectPoint) {
//        Result result = new Result();
//        System.out.println("update参数=" + collectPoint);
//        boolean isok = collectionService.disassociateData(collectPoint);
//        result.setData(isok);
//        result.setData(isok);
//        return result;
//    }


    /**
     * 功能描述 行政区划查询
     */
//    @RequestMapping(value = "/selectGroupAll", method = RequestMethod.POST)
//    public AjaxResult selectGroupAll(@RequestBody CollectPoint collectPoint) {
//        //获取用户的组织
//        Result result = new Result();
//        if (collectPoint.getCreateuserId() != null) {
//            UserEntity userEntity = userService.selectUserById(collectPoint.getCreateuserId());
//            if (userEntity.getOrgid() != null) {
////				List<OrganizeEntity> suborgs = organizeService.getorgbyorgid(userEntity.getOrgid());
////				List<String> orgIds = suborgs.stream().map(i -> i.getId()).collect(Collectors.toList());
////				collectPoint.setOrgIds(orgIds);
//                collectPoint.setOrgId(userEntity.getOrgid());
//            }
//            List<Province> collectPoints = collectionService.selectGroupAll(collectPoint);
//            result.setData(collectPoints);
//        }
//        return result;
//    }


    /**
     * 功能描述 根据时间查询全部
     *
     * @param * @param
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 11:01
     */
//    @RequestMapping(value = "/getListTime", method = RequestMethod.POST)
//    public Result getListTime(@RequestBody CollectPoint collectPoint) {
//        Result result = new Result();
//        if (collectPoint.getCreateuserId() != null) {
//            UserEntity userEntity = userService.selectUserById(collectPoint.getCreateuserId());
//            if (userEntity.getOrgid() != null) {
////				List<OrganizeEntity> suborgs = organizeService.getorgbyorgid(userEntity.getOrgid());
////				List<String> orgIds = suborgs.stream().map(i -> i.getId()).collect(Collectors.toList());
////				collectPoint.setOrgIds(orgIds);
//                collectPoint.setOrgId(userEntity.getOrgid());
//            }
//            List<CollectPoint> collectPointList = collectionService.getListTime(collectPoint);
//            result.setData(collectPointList);
//        }
//        return result;
//    }


    /**
     * 功能描述 查询全部
     *
     * @param * @param
     * @return com.agri.collection_server.util.Result
     * @author shill
     * @date 2021-02-04 10:14
     */
    @PostMapping(value = "/getListGrouping")
    public AjaxResult getListGrouping(@RequestBody CollectPoint collectPoint) {
        List<CollectPoint> collectPointList = collectionService.getListGrouping(collectPoint);
//        if (collectPoint.getCreateuserId() != null) {
//            UserEntity userEntity = userService.selectUserById(collectPoint.getCreateuserId());
//            if (userEntity.getOrgid() != null) {
//                collectPoint.setOrgId(userEntity.getOrgid());
//            }

//        }
        return AjaxResult.success(collectPointList);
    }


    /**
     * 测试加载任务点
     *
     * @return
     */
//    @RequestMapping(value = "/test", method = RequestMethod.POST)
//    public String test() {
//        List<CollectPoint> aaa = collectionService.selectaaaaa();
//        for (CollectPoint a : aaa) {
//            County counties = collectionService.dataMatching(a.getGeom());
//            System.out.println("ssss=" + counties.toString());
//            a.setProvinceCode(counties.getSadcode());
//            a.setProvinceName(counties.getProvince());
//            a.setCityCode(counties.getCadcode());
//            a.setCityName(counties.getCity());
//            a.setCountyCode(counties.getXadcode());
//            a.setCountyName(counties.getCounty());
//            System.out.println("a=" + a.toString());
//            collectionService.updateCollection(a);
//        }
//        return null;
//    }

    /**
     * 生成16位不重复的随机数，含数字+大小写
     *
     * @return
     */
    public static String getGUID() {
        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(3);
            switch (type) {
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
                    break;
                case 1:
                    //ASCII在65-90之间为大写,获取大写随机
                    uid.append((char) (rd.nextInt(25) + 65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写，获取小写随机
                    uid.append((char) (rd.nextInt(25) + 97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }
}
